//
//  SWProfileBookView.swift
//  ChildStory
//
//  Created by linhan on 2017/1/7.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWProfileBookView: UIView
{
    weak var delegate:ClickActionDelegate?
    
    //当前显示的页面的pageID、bookID
    private var _pageID:String = ""
    private var _bookID:String = ""
    private let ImageViewCount:Int = 3
    
    private var _imageViews:[UIImageView] = []
    private var _imageContainer:UIView = UIView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup()
    {
        backgroundColor = UIColor.white
        
        let label:UILabel = UILabel()
        label.text = "宝贝成长故事"
        label.sizeToFit()
        label.frame = CGRectMake(0, 0, label.width, label.height)
        addSubview(label)
        
        let countLabelWidth:CGFloat = 120
        let countLabel:UILabel = UILabel()
        countLabel.textAlignment = .right
        countLabel.frame = CGRectMake(width - countLabelWidth, 0, countLabelWidth, 20)
        addSubview(countLabel)
        
        
        let button:UIButton = UIButton(type:.system)
        button.setTitle("故事书", for: .normal)
        button.sizeToTouchEasy()
        button.center = CGPointMake(width * 0.5, 20)
        button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
        addSubview(button)
        
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
        let imageViewSize:CGSize = CGSizeMake(80, 80)
        _imageContainer.frame = CGRectMake(0, 30, width, imageViewSize.height)
        _imageContainer.backgroundColor = UIColor.lightGray
        _imageContainer.addGestureRecognizer(tapGesture)
        addSubview(_imageContainer)
        
        for i in 0..<ImageViewCount
        {
            let imageView = UIImageView()
            let grid:CGFloat = 10
            imageView.frame = CGRectMake((imageViewSize.width + grid) * CGFloat(i), 0, imageViewSize.width, imageViewSize.height)
            imageView.contentMode = .scaleAspectFill
            imageView.clipsToBounds = true
            _imageContainer.addSubview(imageView)
            _imageViews.append(imageView)
        }
        
        
        
        
        let t1:Double = Date().timeIntervalSince1970
        
        //对本地资源按事件进行分类，但是未导入实体书的
        let assets:[SWAssetRecord] = SWAssetsManager.sharedManager().assets.filter({$0.classified})
        var categories:[String:[SWAssetRecord]] = [:]
        for asset in assets
        {
            let eventID:String = asset.eventID ?? ""
            categories[eventID] = categories[eventID] ?? []
            categories[eventID]?.append(asset)
        }
        
        //按事件分类时间排序
        for (id,assets) in categories
        {
            categories[id] = assets.sorted(by: {$0.classifiedTime > $1.classifiedTime})
        }
        
        //先找出本地资源跟实体书共有的部分
        var unreadList:[(classifiedTime:Int, records:[SWAssetRecord],page:SWPage)] = []
        var list:[(classifiedTime:Int, records:[SWAssetRecord],page:SWPage)] = []
        let books:[SWBook] = SWBookManager.sharedManager().books.filter({$0.category == .event})
        for book in books
        {
            let pages:[SWPage] = book.pages?.flatMap({$0 as? SWPage}) ?? []
            for page in pages
            {
                let eventID:String = page.eventID ?? ""
                
                if let records = categories[eventID]
                {
                    let classifiedTime:Int = records.valueAt(0)?.classifiedTime ?? 0
                    let item = (classifiedTime:classifiedTime, records:records, page:page)
                    if !page.read && page.photoImportedTime == 0
                    {
                        unreadList.append(item)
                    }
                    list.append(item)
                }
                
            }
        }
        
        unreadList.sort(by: {$0.classifiedTime > $1.classifiedTime})
        list.sort(by: {$0.classifiedTime > $1.classifiedTime})
        
        let unreadCount:Int = unreadList.count
        if unreadCount > 0
        {
            countLabel.text = "故事更新x\(unreadCount)"
        }
        
        print("耗时：", Date().timeIntervalSince1970 - t1)
        
        if let item = (unreadList.first ?? list.first)
        {
            let records = item.records
            _pageID = item.page.pageID ?? ""
            _bookID = item.page.bookID ?? ""
            
            let localIdentifiers = records[0..<min(records.count,ImageViewCount)].map({$0}).flatMap({$0.localID})
            
            var options = SWALPhotoRequestOptions()
            options.targetSize = CGSizeMake(100, 100)
            SWAssetsLibraryHelper.shared().fetchOriginImage(localIdentifiers: localIdentifiers, options: options, completeCallback: {[weak self] results in
                
                for (index, result) in results.enumerated()
                {
                    self?._imageViews.valueAt(index)?.image = result.image
                }
            })
        }//end if records
    }
    
    @objc private func buttonTapped()
    {
        //delegate?.view(self, click: CallbackAction.Tap, argument: nil)
    }
    
    @objc private func imageTapped()
    {
        delegate?.view(self, click: CallbackAction.Tap, argument: [SWKey.pageID:_pageID, SWKey.bookID:_bookID])
    }
    
    
}
